package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.StringTokenizer;

public class ClientHandler implements Runnable{
	private Socket clientSocket;
	private String serverName;
	private HashMap<String, Socket> clientList;
	
	public ClientHandler(Socket clientSocket, String serverName, HashMap<String, Socket> clientList) {
		this.clientSocket = clientSocket;
		this.serverName = serverName;
		this.clientList = clientList;
	}
	
	@Override
	public void run() {
		// keep client connection
		while (true){
			String messageReveice = null;
			try {
				messageReveice = receive(clientSocket.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			if (messageReveice == null || messageReveice.isEmpty()) {
				System.out.println("Client " + clientSocket.getRemoteSocketAddress() + " da dong connection");
				return;
			}
			
			System.out.println("Client " + clientSocket.getRemoteSocketAddress() + " da gui tin nhan: " + messageReveice);
			
			// handler received message
			StringTokenizer strtok = new StringTokenizer(messageReveice, ";");
			String des = strtok.nextToken();
			String content = strtok.nextToken();
			
			handlerMessage(clientSocket, des, content);

		}
	}

	public void send(OutputStream os, String message) throws IOException{		
		int messageLength = message.length();
		byte [] messageLengthInByte = ByteBuffer.allocate(4).putInt(messageLength).array();
		
		// send 4 bytes for length
		os.write(messageLengthInByte);
		
		byte [] dataInByte = message.getBytes();
		
		// send data 
		os.write(dataInByte);
	}
	
	public String receive(InputStream is) throws IOException{
		
		byte [] messageLengthInByte = new byte[4];
		
		// read 4 bytes for length
		is.read(messageLengthInByte);
		int messageLength = ByteBuffer.wrap(messageLengthInByte).getInt();
		
		byte [] messageInByte = new byte[messageLength];
		// read data
		is.read(messageInByte);
		String message = new String(messageInByte);
		
		return message;
	}

	private void handlerMessage(Socket clientSocket, String des, String content) {
		if (des.equals(serverName)) {
			// message register
			clientList.put(content, clientSocket);
			System.out.println("Client " + clientSocket.getRemoteSocketAddress() + " da dang ky voi ten: " + content);
		} else {
			// message for other client => forward
			Socket otherClientSocket = clientList.get(des);
			try {
				send(otherClientSocket.getOutputStream(), content);
				System.out.println("Client " + clientSocket.getRemoteSocketAddress() + " da gui den " + des + " a message: " + content);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}



}
